package com.book.bookshop.web;

import com.book.bookshop.entity.User;
import com.book.bookshop.service.UserService;
import com.cloopen.rest.sdk.BodyType;
import com.cloopen.rest.sdk.CCPRestSmsSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Random;
import java.util.Set;

/**
 * @Auther: jzhang
 * @Date: 2019/9/24 15:49
 * @Description: 用户控制器
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    String format= null;

    //验证用户名是否存在
    @ResponseBody
    @RequestMapping("/checkUserName")
    public String checkUserName(String username){
        return userService.checkUser(username);
    }

    /**
     * 用户注册
     */
    @ResponseBody
    @RequestMapping("register")
    public String register( User user,@RequestParam(name = "ma") String ma){

        if (format.equals(ma)){
            userService.save(user);
            return "success";
        }else {
            return "false";
        }

    }
    /**
     * 验证码
     */
    @ResponseBody
    @RequestMapping("yanZheng")
    public String yanZheng(){

        //生产环境请求地址：app.cloopen.com
        String serverIp = "app.cloopen.com";
        //请求端口
        String serverPort = "8883";
        //共有7处地方需要修改
        //修改1 ：管理-->控制台首页中能查到accountSId
        String accountSId = "8a216da87771d1d8017801fe928c0307";
        //修改2 ：管理-->控制台首页中能查到accountToken
        String accountToken = "fd6de5bae4b344da929d8be40c97a129";
        //修改3 ：管理-->应用管理-->应用列表-->应用01-->应用管理,查看appId
        String appId = "8a216da87771d1d8017801fe93ef030e";
        CCPRestSmsSDK sdk = new CCPRestSmsSDK();
        sdk.init(serverIp, serverPort);
        sdk.setAccount(accountSId, accountToken);
        sdk.setAppId(appId);
        sdk.setBodyType(BodyType.Type_JSON);
        //修改4 ：修改接收短信的手机号，手机号要在后台添加进去
        String to = "15536391364";
        //修改5 ：templateId改成1
        String templateId= "1";
        //修改6 ：
        format = String.format("%04d", new Random().nextInt(9999));
        String[] datas = {format,"3"};
        String subAppend="1234";  //可选 扩展码，四位数字 0~9999
        //修改7 ：修改reqId为新的
        Random random = new Random();
        char[] keys = new char[8];
        for (int i = 0; i < keys.length; i++) {
            int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; // 取得大写还是小写
            keys[i] = (char) (choice + random.nextInt(26));
        }
        String s = String.valueOf(keys);
        String reqId=s;  //可选 第三方自定义消息id，最大支持32位英文数字，同账号下同一自然天内不允许重复
        //HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas);
        HashMap<String, Object> result = sdk.sendTemplateSMS(to,templateId,datas,subAppend,reqId);
        if("000000".equals(result.get("statusCode"))){
            //正常返回输出data包体信息（map）
            HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
            Set<String> keySet = data.keySet();
            for(String key:keySet){
                Object object = data.get(key);
                System.out.println(key +" = "+object);
            }
        }else{
            //异常返回输出错误码和错误信息
            System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
            return "false";
        }

        return "success";
    }

    /**
     * 用户登录
     */
    @ResponseBody
    @RequestMapping("/login")
    public String login(User user,HttpSession session){
        return userService.loginCheck(user,session);
    }

    /**
     * 安全退出
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "redirect:/";
    }
}
